package api;

import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.Dish;
import model.ResultData;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 订单详情
 * @author: chengbaiyi
 * @create: 2022-06-26 20:53
 */
@WebServlet("/orderdetail")
public class OrderDetailServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state = -1;
        String msg = "未知错误！";
        List<Dish> data = new ArrayList<>();
        int oid = Integer.parseInt(req.getParameter("oid"));
        if (oid > 0) {
            Connection connection = DBUtil.getConnection();
            String sql = "select * from dish where did in(select did from orderdetail where oid=?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, oid);
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Dish dish = new Dish();
                dish.setName(resultSet.getString("name"));
                dish.setPrice(resultSet.getBigDecimal("price"));
                data.add(dish);
            }
            DBUtil.close(resultSet, statement, connection);
            state = 200;

        } else {
            msg = "参数无效！";
        }
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        resp.getWriter().println(
                JSONUtil.toJsonStr(new ResultData(state, data, msg))
        );
    }
}
